package com.bxw.forum.controller;

import com.bxw.forum.common.AppResult;
import com.bxw.forum.common.ResultCode;
import com.bxw.forum.config.AppConfig;
import com.bxw.forum.model.Message;
import com.bxw.forum.model.User;
import com.bxw.forum.service.IMessageService;
import com.bxw.forum.service.IUserService;
import com.bxw.forum.utils.GetRequest;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private IMessageService messageService;

    @Resource
    private IUserService userService;

    @RequestMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @RequestParam("content") @NonNull String content) {


        //从request中获取postUser
        //校验postUser是否被禁言
        //校验receiveUser是否正常
        //校验是否receiveUser == postUser
        //构造message对象，将数据set
        //调用Service插入数据
        //返回结果

        HttpSession session = request.getSession(false);
        User postUser = (User) session.getAttribute(AppConfig.USER_SESSION);

        if(postUser.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        User receiveUser = userService.selectById(receiveUserId);

        if(receiveUser == null || receiveUser.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());

            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        if(postUser.getId() == receiveUserId) {

            return AppResult.fail("不能给自己发私信");
        }



        Message message = new Message();
        message.setPostUserId(postUser.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);

        messageService.create(message);

        return AppResult.success();
    }

    @RequestMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        // 1. 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 2. 调用Service
        Integer count = messageService.selectUnreadCount(user.getId());// 当前登录用户的Id就是接收者Id

        // 3. 返回结果
        return AppResult.success(count);
    }

    @RequestMapping ("/getAll")
    public AppResult<List<Message>> getAll (HttpServletRequest request) {
        // 1. 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 2. 调用Service
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        // 3. 返回结果
        return AppResult.success(messages);
    }

    @RequestMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @RequestParam(value = "id") @NonNull Long id) {

        Message message = messageService.selectById(id);

        if(message == null || message.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());

            return AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if(user.getId() != message.getReceiveUserId()) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());

            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }

        messageService.updateStateById(id,(byte)1);

        return AppResult.success();
    }

    @RequestMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @RequestParam(value = "repliedId") @NonNull Long repliedId,
                           @RequestParam(value = "content") @NonNull String content) {

        User user = GetRequest.getUser(request);

        if(user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        Message existMessage = messageService.selectById(repliedId);

        if(existMessage == null || existMessage.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());

            return AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }

        if(existMessage.getPostUserId() == user.getId()) {
            log.warn("不能给自己回复");

            return AppResult.fail("不能给自己回复");
        }

        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existMessage.getPostUserId());
        message.setContent(content);

        messageService.reply(repliedId,message);

        return AppResult.success();
    }
}
